import { Component, OnInit, ViewChild } from '@angular/core';
import { Well } from 'src/app/api/appconfig';
import { Table } from 'primeng/table';
import { ConfirmationService, MessageService } from 'primeng/api';
import { AppMainComponent } from 'src/app/app.main.component';
import { Router, NavigationExtras } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { Observable, zip } from 'rxjs';
import { UserState } from 'src/app/store/user/user.model';
import { WellService } from 'src/app/service/well.service';
import { UtilsService } from 'src/app/service/utils.service';
import { getApplicant } from 'src/app/store/utils/utils.reducer';
import { AppState } from 'src/app/store/app.model';
import { transform } from 'src/app/service/utils/transform';
@Component({
    selector: 'app-basic-info',
    templateUrl: './basic-info.component.html',
    styleUrls: ['./basic-info.component.scss'],
    providers: [ConfirmationService, MessageService],
    styles: [
        `
            :host ::ng-deep .p-frozen-column {
                font-weight: bold;
            }

            :host ::ng-deep .p-datatable-frozen-tbody {
                font-weight: bold;
            }

            :host ::ng-deep .p-progressbar {
                height: 0.5rem;
            }
        `,
    ],
})
export class BasicInfoComponent implements OnInit {
    user: any;
    displayPredict = false;
    loading: boolean = true;
    //customers1: Customer[];
    display: boolean = false;
    editTag: boolean = false;
    @ViewChild('dt1') table: Table;
    predictItem:any;
    data: any[];
    address: any[];
    status: any[];
    wellStatus: string;
    searchWellCode: any = '';
    searchWellName: any = '';
    searchAddress: any = '';
    searchApplicantName: any = '';
    searchWellId: any = '';
    applicant: any = [];
    type: any[];
    usage: any[];
    aa:any;
    predictForm = {
        time:new Date(),
        pressure:null,
        temperature:null
    }
    well = {
        wellId:null,
        applicantId: null,
        comNumber: null,
        createTime: null,
        irrigationArea: null,
        latitude: null,
        longitude: null,
        remark: null,
        status: null,
        wellCaliber: null,
        wellCode: null,
        wellDepth: null,
        wellName: null,
        wellType: null,
        wellUsage: null,
        zoneId: null,
        zoneType: null,
    };
    blankwell = {
        wellId:null,
        applicantId: null,
        comNumber: null,
        createTime: null,
        irrigationArea: null,
        latitude: null,
        longitude: null,
        remark: null,
        status: null,
        wellCaliber: null,
        wellCode: null,
        wellDepth: null,
        wellName: null,
        wellType: null,
        wellUsage: null,
        zoneId: null,
        zoneType: null,
    };
    //messageService: any;
    constructor(
        private confirmationService: ConfirmationService,
        private messageService: MessageService,
        public appMain: AppMainComponent,
        private router: Router,
        private store: Store<AppState>,
        private wellService: WellService,
        private utilsService: UtilsService,
        private transform: transform
    ) {
        this.status = transform.statuss;
        this.type = transform.types;
        this.usage = transform.usages;
    }
    genTwoLengthNumberString = (n) => (n >= 10 ? n : '0' + n);
    dateTimeTrans(d) {
        if (typeof d === 'string') {
            return d;
        }
        if (!d) {
            return '';
        }
        let yy = d.getFullYear();
        let MM = this.genTwoLengthNumberString(d.getMonth() + 1);
        let dd = this.genTwoLengthNumberString(d.getDate());
        let hh = this.genTwoLengthNumberString(d.getHours());
        let mm = this.genTwoLengthNumberString(d.getMinutes());
        let ss = this.genTwoLengthNumberString(d.getSeconds());
        return yy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss;
    }
    setZone(){
        this.well.zoneType = this.aa.isArea?1:2
        this.well.zoneId = this.aa.isArea?this.aa.id:this.aa
        console.log(this.well.zoneType,this.well.zoneId)
    }
    ngOnInit(): void {
        //this.onUser()
        this.store.pipe(select(getApplicant)).subscribe((data) => {
            this.applicant = data;
            console.log(this.applicant);
        });
        this.search();
        this.address = this.utilsService.addressOption();
        console.log(this.address);
    }
    showDialog() {
        this.editTag = false;
        this.display = !this.display;
        this.well = {
            ...this.blankwell
        };
    }
    showDialog2(item) {
        this.editTag = true;
        this.display = !this.display;
        this.well = {
            ...item,
        };
    }
    deleteWell(item) {
        //console.log("ok")
        this.confirmationService.confirm({
            message: '请问你确认删除吗 ?',
            header: '警告',
            icon: 'pi pi-exclamation-triangle',
            accept: async () => {
                const res = await this.wellService.deleteWellInfoById({
                    well_ids: item.wellId,
                });
                if (res.code == 200) {
                    this.messageService.add({
                        severity: 'info',
                        summary: '确认',
                        detail: '你已经删除',
                    });
                    this.search();
                }
            },
        });
    }
    goToFile(a) {
        let navigationExtras: NavigationExtras = {
            queryParams: { id: a.wellId },
        };
        this.router.navigate(['/pages/file'], navigationExtras);
    }
    async search() {
        //console.log('searchWellCode', this.searchWellCode);
        //console.log('searchWellName', this.searchWellName);
        //console.log('searchApplicantName', this.searchApplicantName);
        //console.log('searchAddress', this.searchAddress);
        const res = await this.wellService.fetchWellInfoByConfig({
            wellCode: this.searchWellCode || undefined,
            wellName: this.searchWellName || undefined,
            applicantName: this.searchApplicantName || undefined,
            address: this.searchAddress || undefined,
            wellId: this.searchWellId || undefined,
        });
        this.data = res.data;
        this.data.forEach((item)=>{
            item.createTime = new Date(item.createTime)
        })
        console.log(this.data);
    }
    async reset() {
        this.searchWellCode = '';
        this.searchWellName = '';
        this.searchApplicantName = '';
        this.searchAddress = '';
        this.search();
    }
    async handleStatus(row) {
        console.log(row);
        let nextStatus;
        if (row.status === 1002 || row.status === 1003) {
            nextStatus = 1001;
        } else if (row.status === 1001 || row.status === 4444) {
            nextStatus = 1003;
        } else {
            return;
        }
        const res = await this.wellService.updateWellInfoByConfig({
            ...row,
            status: nextStatus,
            createTime:this.dateTimeTrans(row.createTime)
        });
        if (res.code == 200) {
            this.messageService.add({
                severity: 'success',
                summary: '成功',
                detail: '已经修改了对应的阀门状态',
            });
        }
        this.search();
    }
    async handleDelete(row) {
        var temp = confirm('此操作将永久删除该数据, 是否继续?');
        if (temp) {
            let i = 0;
            const res = await this.wellService.deleteWellInfoById({
                well_ids: row.id,
            });
            if (res.code == 200) {
                this.messageService.add({
                    severity: 'success',
                    summary: '成功',
                    detail: '已经删除了对应的阀门',
                });
            }
            this.search();
        }
    }
    async comfirmAdd() {
        console.log(this.aa)
        for (let item in this.well) {
            if (!this.well[item] && item != 'phone' && item != 'remark'&&item!='wellId') {
                console.log(item);
                this.messageService.add({
                    severity: 'error',
                    summary: '警告',
                    detail: '存在为空的项',
                });
                return;
            }
        }
        if (this.editTag) {
            console.log(this.well)
            this.well = {
                ...this.well,
                createTime:this.dateTimeTrans(this.well.createTime)
            }
            const res = await this.wellService.updateWellInfoByConfig(this.well)
            if (res.code == 200){
                this.messageService.add({
                    severity: 'success',
                    summary: '成功',
                    detail: '已经修改了对应的阀门信息',
                });
                this.display = false;
                this.search()
            }else{
                this.messageService.add({
                    severity: 'error',
                    summary: '失败',
                    detail: '请检查网络连接',
                });
            }
        }
        if (!this.editTag) {
            this.well = {
                ...this.well,
                createTime:this.dateTimeTrans(this.well.createTime)
            }
            console.log(this.well)
            const res = await this.wellService.addWellInfoByConfig(this.well);
            if (res.code == 200) {
                this.messageService.add({
                    severity: 'success',
                    summary: '成功',
                    detail: '已经新增了阀门',
                });
                this.display = false;
                this.search()
            }else{
                this.messageService.add({
                    severity: 'error',
                    summary: '失败',
                    detail: '请检查网络连接',
                });
            }
        }
    }
    openPredict(){
        this.displayPredict = true;
        this.predictForm.time = new Date()
        this.predictForm.pressure = null
        this.predictForm.temperature = null
        this.predictItem = null
    }
    async predict(){
        console.log(this.predictItem)
        const res = await this.wellService.predictWell({
            hour:this.predictForm.time.getHours(),
            minute:this.predictForm.time.getMinutes(),
            temperature:this.predictForm.temperature,
            pressure:this.predictForm.pressure
        })
        console.log(res)
        if(res.data){
            this.displayPredict = false
            const res1 = await this.wellService.updateWellInfoByConfig({
                ...this.predictItem,
                status: 4444,
                createTime:this.dateTimeTrans(this.predictItem.createTime)
            });
            if (res1.code == 200) {
                this.messageService.add({
                    severity: 'error',
                    summary: '警告',
                    detail: '该阀门正在报警',
                });
            }
            this.search();
        }else{
            this.displayPredict = false
            this.messageService.add({
                severity: 'success',
                summary: '注意',
                detail: '阀门压力在安全范围内',
            });
        }
    }
}
